package com.powernode.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import com.powernode.util.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName AuthFilter
 * @Description 全局token过滤器 -- 前端后端约定好令牌存放的位置： 请求头的 Authorization bearer token
 * @Date 2024/07/20 13:34
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Resource
    private WhiteUrlsConfig whiteUrlsConfig;
    @Resource
    private RedisCache redisCache;

    /**
     * 校验token
     * 1. 获取请求路径
     * 2. 判断请求路径是否可以放行
     *    放行：不需要验证身份
     *    不放行：需要验证身份
     *
     * @param exchange 上下文
     * @param chain 过滤链
     * @return 结果
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getPath().toString();
        // 判断当前请求路径是否需要放行，是否存在于白名单中
        if (whiteUrlsConfig.getAllowUrls().contains(path)) {
            // 请求路径包含在白名单中，放行
            return chain.filter(exchange);
        }
        // 请求路径不包含在白名单中，验证  从约定好的位置获取Authorization 格式：bearer token
        String authorizationValue = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        if (StringUtils.hasText(authorizationValue)) {
            String tokenValue = authorizationValue.replaceFirst(AuthConstants.AUTHORIZATION_PREFIX, "");
            // token是否有值且在redis中存在
            // redisCache.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + tokenValue)
            if (StringUtils.hasText(tokenValue)) {
                // 身份验证通过
                return chain.filter(exchange);
            }
        }
        // 验证身份失败，或请求不合法
        log.error("拦截非法请求，时间：{}，请求API路径：{}", new Date(), path);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);
        // 创建objectMapper对象
        byte[] bytes = new byte[0];
        try {
            bytes = new ObjectMapper().writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
